// MLSDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MLS.h"
#include "MLSDlg.h"
#include "CodeDlg.h"
#include "MLSScanner.h"
#include "RTFWriter.h"
#include "MLSParser.h"
#include "FileDialogST.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CMLSDlg dialog



CMLSDlg::CMLSDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CMLSDlg::IDD, pParent)
	, FileName(_T(""))
	, PrevDoc(_T(""))
	, NextDoc(_T(""))
/*	, PrevDoc(_T(""))
	, FileName(_T(""))
	*/, PathName(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMLSDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_NEXT, NextDoc);
	DDX_Text(pDX, IDC_PREV, PrevDoc);
	DDX_Text(pDX, IDC_FILENAME, FileName);
	DDX_Control(pDX, IDC_DOCLIST, DocList);
	DDX_Text(pDX, IDC_PATH, PathName);
}

BEGIN_MESSAGE_MAP(CMLSDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BROWSE, OnBnClickedBrowse)
	ON_LBN_SELCHANGE(IDC_DOCLIST, OnLbnSelchangeDoclist)
	ON_BN_CLICKED(IDC_CODE, OnBnClickedCode)
	ON_BN_CLICKED(IDC_PREVIEWSEL, OnBnClickedPreviewsel)
	ON_BN_CLICKED(IDC_MOVE, OnBnClickedMove)
	ON_BN_CLICKED(IDC_SETFIRST, &CMLSDlg::OnBnClickedSetfirst)
	ON_BN_CLICKED(IDC_BYPAGE, &CMLSDlg::OnBnClickedBypage)
	ON_BN_CLICKED(IDC_PREVIEW, &CMLSDlg::OnBnClickedPreview)
	ON_BN_CLICKED(IDC_HTML, &CMLSDlg::OnBnClickedHtml)
	ON_BN_CLICKED(IDC_RTF, &CMLSDlg::OnBnClickedRtf)
END_MESSAGE_MAP()


// CMLSDlg message handlers

BOOL CMLSDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// DS
	OnLbnSelchangeDoclist();
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMLSDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMLSDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMLSDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CMLSDlg::OnBnClickedBrowse()
{
	CFileDialog dlg(TRUE);
	if(dlg.DoModal()==IDCANCEL) return;
	Chain.SetStartDoc(dlg.GetPathName());
	BOOL bChainOK = Chain.LoadChain();
	if(!bChainOK)
	{
		AfxMessageBox(Chain.GetError());
		bChainOK = Chain.GetCount()!=0;
	}
	DocList.ResetContent();
	if(bChainOK)
	{
        for(int n=0;n<Chain.GetCount();n++)
			DocList.AddString(Chain.GetItem(n));
		DocList.SetCurSel(0);
		OnLbnSelchangeDoclist();
		FileName = dlg.GetPathName();
	}
	else
	{
		PathName.Empty();
		NextDoc.Empty();
		PrevDoc.Empty();
		FileName.Empty();
	}
	UpdateData(FALSE);
	GetDlgItem(IDC_PREVIEW)->EnableWindow(bChainOK);
	//GetDlgItem(IDC_HTML)->EnableWindow(bChainOK);
	GetDlgItem(IDC_RTF)->EnableWindow(bChainOK);
	GetDlgItem(IDC_MOVE)->EnableWindow(bChainOK);
	GetDlgItem(IDC_CODE)->EnableWindow(bChainOK);
	GetDlgItem(IDC_SETFIRST)->EnableWindow(bChainOK);
	GetDlgItem(IDC_BYPAGE)->EnableWindow(bChainOK);
	GetDlgItem(IDC_PREVIEWSEL)->EnableWindow(bChainOK);
}

void CMLSDlg::OnLbnSelchangeDoclist()
{
	int n = DocList.GetCurSel();
	if(n!=LB_ERR)
	{
		PathName = Chain.GetItemPath(n);
		NextDoc = Chain.GetItemNext(n);
		PrevDoc = Chain.GetItemPrev(n);
	}
	UpdateData(FALSE);
}

void CMLSDlg::OnBnClickedCode()
{
	CCodeDlg CodeDlg;
	CodeDlg.FileName = Chain.GetItem(DocList.GetCurSel());
	CodeDlg.IsCode = TRUE;
	CString FileName = Chain.GetItemPath(DocList.GetCurSel());
	CMLSScanner Scanner;
	if(!Scanner.Open(FileName)){AfxMessageBox(_T("Error openning file!"));return;}

	CRTFWriter Output;
	Output.SetTarget(&CodeDlg.RichText);
	int StateLang;
	Output.StartDocument(CRichWriter::Arabic);
	Output.StartFontTable();
	Output.AddFont(CRTFWriter::ff_swiss,"Courier New");
	Output.AddFont(CRTFWriter::ff_swiss,"Arial");
	Output.AddFont(CRTFWriter::ff_nill,"Athanasius",0);
	Output.EndFontTable();

	StateLang = Scanner.GetLangAhead();
	Output.StartParagraph(CRichWriter::RichLanguage(StateLang&1));
	Output.SetFont(StateLang&0x07);

	while(Scanner.GetToken() != CMLSScanner::mlstk_EndOfFile)
	{
		if(Scanner.GetRaw()==0x80)
		{
			Output.EndParagraph();
			Output.StartParagraph(CRichWriter::RichLanguage(Scanner.GetLangAhead()&1),(StateLang==1)?CRichWriter::Right:CRichWriter::Left);
		}
		else
		{
			if(Scanner.GetLanguage()!=StateLang&&Scanner.GetTarget()!='/')
			{
				Output.SetLang(CRichWriter::RichLanguage(StateLang=Scanner.GetLanguage()));
				Output.SetFont(StateLang&0x07);
			}
			if(Scanner.GetLanguage()==2&&Scanner.GetTarget()=='|')
				CodeDlg.RichText += "{\\f0|}";
			else if(Scanner.GetLanguage()==2&&Scanner.GetTarget()=='/')
				CodeDlg.RichText += "{\\f0/}";
			else
			{
				WCHAR chr=Scanner.GetTarget();
				if(chr&0xFF00)
					Output.AddChar((char)chr);//WCHAR Support not yet
				else
					Output.AddChar((char)chr);
			}
		}
	}
	Output.EndParagraph();
	Output.EndDocument();
	CodeDlg.DoModal();
}

void CMLSDlg::OnBnClickedPreviewsel()
{
	CCodeDlg CodeDlg;
	CodeDlg.FileName = Chain.GetItem(DocList.GetCurSel());
	CodeDlg.IsCode = FALSE;
	CString FileName = Chain.GetItemPath(DocList.GetCurSel());
	CMLSParser Parser;
	CRTFWriter RTFWriter;
	RTFWriter.SetTarget(&CodeDlg.RichText);
	if(Parser.ParseFile(FileName,&RTFWriter))
		CodeDlg.DoModal();
}

void CMLSDlg::OnBnClickedMove()
{
	CFileDialogST FileDlg;
	if(FileDlg.SelectFolder("Select Target Folder")==IDOK)
	{
        CString Path = FileDlg.GetSelectedFolder();
		// Move Chain
		if (Chain.MoveAll(Path))
			AfxMessageBox("Moved Successfully");
		else
			AfxMessageBox("Error Moving");
	}
}


void CMLSDlg::OnBnClickedSetfirst()
{
	// TODO: Add your control notification handler code here
}


void CMLSDlg::OnBnClickedBypage()
{
	// TODO: Add your control notification handler code here
}


void CMLSDlg::OnBnClickedPreview()
{
	CCodeDlg CodeDlg;
	CodeDlg.FileName = "All Chain";
	CodeDlg.IsCode = FALSE;
	CRTFWriter RTFWriter;
	RTFWriter.SetTarget(&CodeDlg.RichText);

	CMLSParser Parser;

	if(Parser.ParseChain(&Chain,&RTFWriter))
		CodeDlg.DoModal();
}


void CMLSDlg::OnBnClickedHtml()
{
	/*CFileDialog fldlg(FALSE,_T("html"),FileName+_T(".html"),OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,_T("Hyper Text Markup Language (*.html)|*.html||"));
	if(fldlg.DoModal()==IDOK)
	{
		CFile file;
		if(file.Open(fldlg.GetPathName(),CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive))
		{
			CHTMLWriter HTMLWriter;
			HTMLWriter.SetTarget(&file);

			CMLSParser Parser;

			if(Parser.ParseChain(&Chain,&HTMLWriter))
				AfxMessageBox(_T("Successfully Converted"));
			else
				AfxMessageBox(_T("Error converting to HTML"));
		}
		else AfxMessageBox(_T("Cannot open file for writting"));
	}*/
}


void CMLSDlg::OnBnClickedRtf()
{
	CFileDialog fldlg(FALSE,_T("rtf"),FileName+_T(".rtf"),OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,_T("Rich Text Format (*.rtf)|*.rtf||"));
	if(fldlg.DoModal()==IDOK)
	{
		CFile file;
		if(file.Open(fldlg.GetPathName(),CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive))
		{
			CRTFWriter RTFWriter;
			RTFWriter.SetTarget(&file);

			CMLSParser Parser;

			if(Parser.ParseChain(&Chain,&RTFWriter))
				AfxMessageBox(_T("Successfully Converted"));
			else
				AfxMessageBox(_T("Error converting to RTF"));
		}
		else AfxMessageBox(_T("Cannot open file for writting"));
	}
}
